<template>
  <div>
    <el-card>
      <SearchItem @search="searchUser" :searchTitle></SearchItem>
    </el-card>
    <el-card style="margin-top: 20px">
      <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
      <el-button
        type="primary"
        size="default"
        :disabled="selectIdArr.length ? false : true"
        @click="deleteSelectUser"
        >批量删除</el-button
      >
      <el-table border @selection-change="selectChange" :data="userData" style="margin: 20px 0">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column label="用户名字" align="center" prop="name"></el-table-column>
        <el-table-column label="用户名称" align="center" prop="username"></el-table-column>
        <el-table-column label="用户角色" align="center" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="User" @click="setRole(row)"
              >分配角色</el-button
            >
            <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`你确定要删除${row.username}?`"
              width="260px"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next, jumper,->,sizes,total"
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[8, 12, 16, 20]"
        @current-change="getHasUser"
        @size-change="getHasUser"
      />
    </el-card>
    <el-drawer v-model="dialog" class="demo-drawer">
      <template #header>
        <h4>
          {{
            diglogState === 'add' ? '添加用户' : diglogState === 'update' ? '更新用户' : '分配权限'
          }}
        </h4>
      </template>
      <div class="demo-drawer__content">
        <el-form :model="updateForm" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              v-model="updateForm.username"
              autocomplete="off"
              :disabled="diglogState === 'setR' ? true : false"
            />
          </el-form-item>
          <el-form-item label="用户昵称" prop="name" v-if="diglogState !== 'setR'">
            <el-input v-model="updateForm.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="diglogState === 'add'">
            <el-input v-model="updateForm.password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="职位列表" v-if="diglogState === 'setR'">
            <el-checkbox
              @change="handleCheckAllChange"
              v-model="checkAll"
              :value="checkAll"
              :indeterminate="isIndeterminate"
              >全选</el-checkbox
            >
            <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="(role, index) in allRole" :key="index" :value="role">{{
                role.roleName
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer
        ><div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中 ...' : '确定' }}
          </el-button>
        </div></template
      >
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import SearchItem from '@/components/SearchItem.vue'
import {
  reactive,
  toRefs,
  ref,
  onMounted,
  defineCustomElement,
  useTemplateRef,
  nextTick,
} from 'vue'
import { reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqRemoveUser } from '@/api/acl/user'
import type { AllRole, AllRoleResponseData, User } from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import { update } from 'lodash'
import { Search } from '@element-plus/icons-vue'

onMounted(() => {
  getHasUser()
})

let searchTitle = ref('用户名')

let pageNo = ref<number>(1)
let pageSize = ref<number>(8)
let total = ref<number>(0)
let keyword = ref('')
let userData = ref()
const getHasUser = async (page = 1) => {
  pageNo.value = page
  let res = await reqUserInfo(pageNo.value, pageSize.value, keyword.value)
  if (res.code === 200) {
    userData.value = res.data.records
    total.value = res.data.total
  }
}

let dialog = ref(false)
let diglogState = ref('')
let formRef = useTemplateRef<any>('formRef')
let updateForm = reactive<User>({ name: '', username: '', password: '' })
const updateUser = (row: User) => {
  dialog.value = true
  diglogState.value = 'update'
  Object.assign(updateForm, row)
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}

const addUser = () => {
  dialog.value = true
  diglogState.value = 'add'
  //清空数据
  Object.assign(updateForm, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    //@ts-ignore
    formRef.value.clearValidate('username')
    //@ts-ignore
    formRef.value.clearValidate('name')
    //@ts-ignore
    formRef.value.clearValidate('password')
  })
}

let loading = ref(false)
const onClick = async () => {
  loading.value = true
  //@ts-ignore
  formRef?.validate()

  let SetRoleData = {
    userId: updateForm.id,
    roleIdList: userRole.value?.map((item) => item.id),
  }
  if (diglogState.value === 'setR') {
    console.log(SetRoleData)
    loading.value = false
  } else {
    console.log(updateForm)
    loading.value = false
  }
}
const cancelForm = () => {
  dialog.value = false
}

let allRole = ref<AllRole>()
let userRole = ref<AllRole>()
const setRole = async (row: any) => {
  let res = await reqAllRole(row.id)
  if (res.code === 200) {
    //存储全部的职位
    allRole.value = res.data.allRolesList
    //存储当前用户已有的职位
    userRole.value = res.data.assignRoles
    Object.assign(updateForm, row)
    dialog.value = true
    diglogState.value = 'setR'
  }
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}

let checkAll = ref(false)
let isIndeterminate = ref(true)
const handleCheckAllChange = (value: boolean) => {
  isIndeterminate.value = false
  userRole.value = value ? allRole.value : []
}
const handleCheckedCitiesChange = (value: string[]) => {
  console.log(allRole.value)
  checkAll.value = value.length === allRole.value?.length
  isIndeterminate.value = value.length !== allRole.value?.length
}

let selectIdArr = ref<User[]>([])
const selectChange = () => {}
const deleteSelectUser = () => {}
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getHasUser(userData.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}

const handleClose = () => {}
//校验用户名字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
//校验用户名字回调函数
const validatorname = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
const validatorPassword = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
//表单校验的规则对象
const rules = reactive({
  //用户名字
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  //用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
  //用户的密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
})

//搜索按钮的回调
const searchUser = (word: string) => {
  keyword.value = word
  //根据关键字获取相应的用户数据
  getHasUser()
}
</script>
<style scoped lang="scss"></style>
